package com.tile.v2;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;


public class DownloadThread{
	Tile tile;
	String despath;
	String servicepath;
	private LevelTile lt;
	
	public DownloadThread(){}
	public DownloadThread(Tile tile, String despath, String servicepath, LevelTile lt){
		this.tile = tile;
		this.despath = despath;
		this.servicepath = servicepath;
		this.lt = lt;
	}
	
	public void run() {
		String filepath = despath + tile.getZoom()+"\\"+tile.getY()+"\\s_"+tile.getZoom()+"_"+tile.getX()+"_"+tile.getY()+".png";
		File file = new File(filepath);
		if(file.exists()){
			//System.out.println("文件"+filepath+"已经存在");
			return ;
		}
		String imgurl = servicepath + tile.getURL();
		//System.out.println(imgurl);
		
		URLConnection connection = null;
        try {
        	URL u = new URL(imgurl);
        	connection = u.openConnection();
        	
        	connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:5.0.1) Gecko/20100101 Firefox/5.0.1");
    		connection.setRequestProperty("Accept-Language", "zh-cn,en-US;q=0.5");
    		connection.connect();
    		File dir = new File(file.getParent());
    		if(!dir.exists()){
    			dir.mkdirs();
    		}

    		InputStream is = connection.getInputStream();
    		OutputStream os = new FileOutputStream(file);

        	int len = -1;
    		byte[] data = new byte[3 * 1024];
    		while((len = is.read(data)) != -1){
    			os.write(data, 0, len);
    		}
    		is.close();
    		os.close();

        } catch (Exception e) {
        	e.printStackTrace();
        	file.delete();
        	System.out.println("缺少"+filepath);
        	
        	this.lt.downloadLostTiles(tile, filepath);
        } finally {

        }
	}
}
